import { createError } from "../error.js";
import User from "../models/User.js";
import Video from "../models/Video.js";

export const update = async (req, res, next) => {
  if (req.params.id === req.user.id) {
    try {
      const updateUser = await User.findByIdAndUpdate(
        req.params.id,
        {
          $set: req.body,
        },
        {
          new: true,
        }
      );
      res.status(200).json(updateUser);
    } catch (err) {
      next(err);
    }
  } else {
    return next(createError(403, "你只能更新你自己的用户信息！"));
  }
};

export const deleteUser = async (req, res, next) => {
    if (req.params.id === req.user.id) {
        try {
          await User.findByIdAndDelete(req.params.id)
          res.status(200).json("用户已经被删除");
        } catch (err) {
          next(err);
        }
      } else {
        return next(createError(403, "你只能删除自己！"));
      }
};

export const getUser = async(req, res, next) => {
  try {
    const user=await User.findById(req.params.id)
    res.status(200).json(user)
  } catch (error) {
    next(error)
  }
};
export const subscribe = async(req, res, next) => {
  try {
    await User.findByIdAndUpdate(req.user.id,{
        $push:{subscribedUsers:req.params.id}
    })
    await User.findByIdAndUpdate(req.params.id,{
        $inc:{subscribers:1}
    })
    res.status(200).json("订阅成功！")
  } catch (error) {
    next(error)
  }
};

export const unsubscribe = async(req, res, next) => {
  try {
    try {
        await User.findByIdAndUpdate(req.user.id,{
            $pull:{subscribedUsers:req.params.id}
        })
        await User.findByIdAndUpdate(req.params.id,{
            $inc:{subscribers:-1}
        })
        res.status(200).json("取消订阅成功！")
      } catch (error) {
        next(error)
      }
  } catch (error) {
    next(error)
  }
};

export const like = async(req, res, next) => {
  const id=req.user.id;
  const videoId=req.params.videoId;
  try {
    await Video.findByIdAndUpdate(videoId,{
      $addToSet:{likes:id},
      $pull:{dislikes:id}
    })
    res.status(200).json("这条视频已经被喜欢")
  } catch (error) {
    next(error)
  }
};

export const dislike = async(req, res, next) => {
  const id=req.user.id;
  const videoId=req.params.videoId;
  try {
    await Video.findByIdAndUpdate(videoId,{
      $addToSet:{dislikes:id},
      $pull:{likes:id}
    })
    res.status(200).json("这条视频已经被不喜欢")
  } catch (error) {
    next(error)
  }
};
